package com.study.experiment06;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;

import javax.servlet.ServletContext;

public class Login3 extends ActionSupport implements ModelDriven<User> {
    private User user = new User();

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String login() {
        if ("admin".equals(user.getUsername()) && "sise".equals(user.getPassword())) {
            int onlineUserCount = 0;
            ServletContext servletContext = ServletActionContext.
                    getServletContext();
            synchronized (servletContext) {
                try {
                    Object obj = servletContext.getAttribute("onlineUserCount");
                    onlineUserCount = (Integer) (obj != null ? obj : 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                servletContext.setAttribute("onlineUserCount",
                        onlineUserCount + 1);
            }
            return "success";
        } else {
            return "input";
        }

    }

    public String logout() {
        int onlineUserCount = 0;
        ServletContext servletContext = ServletActionContext.
                getServletContext();
        synchronized (servletContext) {
            try {
                onlineUserCount = (Integer) servletContext
                        .getAttribute("onlineUserCount");
            } catch (Exception e) {
            }
            servletContext.setAttribute("onlineUserCount",
                    onlineUserCount - 1);
        }
        return "success";
    }

    @Override
    public User getModel() {
        return user;
    }

    @Override
    public void validate() {
        if ("".equals(user.getUsername())) {
            this.addFieldError("user.username", "用户名不能为空!");
        }
        if ("".equals(user.getPassword())) {
            this.addFieldError("user.password", "密码不能为空!");
        }
        if (!"admin".equals(user.getUsername())) {
            this.addFieldError("user.username", "用户名输入错误!");
        }
        if (!"sise".equals(user.getPassword())) {
            this.addFieldError("user.password", "密码输入错误!");
        }
    }
}

